package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.exception.CustException;
import com.heima.fegins.AdminFeign;
import com.heima.model.common.constants.WemediaConstants.WemediaConstants;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    WmNewsMapper wmNewsMapper;
    @Value("${file.oss.web-site}")
    String website;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    AdminFeign adminFeign;
    @Override
    public void autoScanWmNews(Integer wmNewsId) {
        log.info(" 自动审核发布方法 被调用   当前审核发布的文章id==> {}", wmNewsId);
        if (wmNewsId == null) {
            log.error("自动审核文章失败    文章id为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = wmNewsMapper.selectById(wmNewsId);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Short status = wmNews.getStatus();
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(status)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        // 抽取出文章中 所有的文本内容 和 所有的图片url集合    Map<String,Object>  content 内容   images List<String>
        Map<String, Object> contentAndImage = handleTextAndImages(wmNews);
        boolean isSensitive=handleSensitive((String)contentAndImage.get("content"),wmNews);
        if (!isSensitive)return;
        boolean isTextScan=handleText((String)contentAndImage.get("content"),wmNews);
        if (!isTextScan) return;
        boolean isImageScan=handleImage((List<String>) contentAndImage.get("images"),wmNews);
        if (!isImageScan)return;
        updateWeNews(wmNews,WmNews.Status.SUCCESS.getCode(),"审核成功");
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());


    }
    @Autowired
    GreenImageScan greenImageScan;
    private boolean handleImage(List<String> images, WmNews wmNews) {
        boolean flag=true;
        try {
            Map map = greenImageScan.imageUrlScan(images);
            String  suggestion =(String) map.get("suggestion");
            switch (suggestion){
                case "review":
                    updateWeNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"转为人工审核");
                    flag=false;
                    break;
                case "block":
                    updateWeNews(wmNews,WmNews.Status.FAIL.getCode(),"发表失败，有违规内容");
                    flag=false;
                    break;

            }

        } catch (Exception e) {
            e.printStackTrace();

            updateWeNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"转为人工审核");
            flag=false;

        }

        return flag;
    }

    @Autowired
    GreenTextScan greenTextScan;
    private boolean handleText(String content, WmNews wmNews) {
        boolean flag=true;
        try {
            Map map = greenTextScan.greenTextScan(content);
            String  suggestion =(String) map.get("suggestion");
            switch (suggestion){
                case "review":
                    updateWeNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"转为人工审核");
                    flag=false;
                    break;
                case "block":
                    updateWeNews(wmNews,WmNews.Status.FAIL.getCode(),"发表失败，有违规内容");
                    flag=false;
                    break;

            }
        } catch (Exception e) {
            e.printStackTrace();
            updateWeNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"转为人工审核");
            flag=false;
        }
        return flag;

    }

    private boolean handleSensitive(String content, WmNews wmNews) {
        ResponseResult<List<String>> sensitivesResult = adminFeign.selectAllSensitives();
        if (sensitivesResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        List<String> sensitives = sensitivesResult.getData();
        SensitiveWordUtil.initMap(sensitives);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map!=null&&map.size()>0){
            updateWeNews(wmNews,WmNews.Status.FAIL.getCode(),"敏感词:"+map.toString());
            return false;
        }
        return true;
    }

    private void updateWeNews(WmNews wmNews, short status, String msg) {
        wmNews.setReason(msg);
        wmNews.setStatus(status);
        wmNewsMapper.updateById(wmNews);
    }

    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        Map<String, Object> result = new HashMap<>();
        String contentJson = wmNews.getContent();
        List<Map> contentMaps = JSONArray.parseArray(contentJson, Map.class);
        StringBuilder content = new StringBuilder(wmNews.getTitle());
        contentMaps.stream().filter(map -> "text".equals(map.get("type")))
                .map(o -> (String) o.get("value")).forEach((text) -> content.append("_hm_" + text));
        result.put("content", content.toString());
        List<String> images = contentMaps.stream().filter(map -> "image".equals(map.get("type")))
                .map(o -> (String) o.get("value"))
                .collect(Collectors.toList());
        if (StringUtils.isNotBlank(wmNews.getImages())){
            List<String> coverImage = Arrays.stream(wmNews.getImages().split(","))
                    .map(url -> website + url).collect(Collectors.toList());
            images.addAll(coverImage);

        }
        images = images.stream().distinct().collect(Collectors.toList());
        result.put("images",images);
        return result;

    }
}


